package main

import (
	"fmt"
	"gitee.com/huanminabc/go-utils/file"
	"gitee.com/huanminabc/go-utils/structure"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
)

var interfaceHandles = []interface{}{
	getCompressContext,
	getConfuseCompressContext,
}

type CompressParams struct {
	// 压缩内容
	Context string `json:"context" form:"context"`
	// 后缀
	Postfix string `json:"postfix" form:"postfix"`
}

var myMinify = NewMinify()

// 用户传递内容进行压缩
func getCompressContext(engine *gin.Engine) {
	engine.POST("/compress", func(c *gin.Context) {
		//json
		var p CompressParams
		if err := c.ShouldBindJSON(&p); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		//压缩
		result := compressContext(myMinify, p.Context, p.Postfix)
		c.JSON(http.StatusOK, structure.Success(result))

	})
}

// 用户上传文件进行压缩 , 这个不准备使用, 因为前端这个使用场景不多,都是直接复制粘贴
func getCompressFile(engine *gin.Engine) {
	engine.POST("/compressFile", func(c *gin.Context) {
		//获取文件
		fileUpdate, err := c.FormFile("file")
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		//读取文件内容
		src, err := fileUpdate.Open()
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		defer src.Close()
		//获取后缀
		postfix := file.GetFileSuffix(fileUpdate.Filename)
		//读取文件内容
		b, err := io.ReadAll(src)
		if err != nil {
			panic(err)
		}
		//压缩
		result := compressContext(myMinify, string(b), postfix)
		c.JSON(http.StatusOK, structure.Success(result))

	})
}

// 用户传递内容进行混淆和压缩
func getConfuseCompressContext(engine *gin.Engine) {
	engine.POST("/confuseCompress", func(c *gin.Context) {
		//json
		var p CompressParams

		if err := c.ShouldBindJSON(&p); err != nil {
			//判断是否是.js
			if p.Postfix != ".js" {
				err = fmt.Errorf("只支持js文件混淆")
			}
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		//混淆
		result := confuseJsContent(p.Context)
		//压缩
		result = confuseJsContent(result)
		c.JSON(http.StatusOK, structure.Success(result))
	})
}
